/**
 * 
 */
package com.ld.tamp.web.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;

import com.ld.base.support.PropertyHolder;
import com.ld.tamp.web.bean.ComponentAccessToken;
import com.ld.tamp.web.constant.WeiXinConstant;
import com.ld.tamp.web.dao.ComponentAccessTokenDao;
import com.ld.tamp.web.dao.ComponentVerifyTicketDao;
import com.ld.tamp.web.event.ReceiveComponentVerifyTicketEvent;
import com.ld.tamp.web.support.ComponentTokenManager;

import weixin.popular.api.ComponentAPI;

/**
 * @author KeYang
 *
 */
public class ReceiveComponentVerfiyTicketListener implements ApplicationListener<ReceiveComponentVerifyTicketEvent>{

	private static final Logger logger = LoggerFactory.getLogger(ComponentTokenManagerListener.class);
	
	@Autowired
	private ComponentVerifyTicketDao componentVerifyTicketDao;

	@Autowired
	private ComponentAccessTokenDao componentAccessTokenDao;
	
	@Override
	public void onApplicationEvent(ReceiveComponentVerifyTicketEvent event) {
		
		
		String componentAppsecret = PropertyHolder.getProperty(WeiXinConstant.COMPONENT_APPSECRET);
		String componentAppid = PropertyHolder.getProperty(WeiXinConstant.COMPONENT_APPID);
		
		String componentVerifyTicket = event.getComponentVerifyTicket();
		
		ComponentAccessToken componentAccessToken=null;
		
		weixin.popular.bean.component.ComponentAccessToken newComponentAccessToken = ComponentAPI.api_component_token(componentAppid,
				componentAppsecret,componentVerifyTicket);
		if(newComponentAccessToken.isSuccess()){
			componentAccessToken = new ComponentAccessToken();
			componentAccessToken.setComponentAccessToken(newComponentAccessToken.getComponent_access_token());
			componentAccessToken.setExpiresTime(new Long(newComponentAccessToken.getExpires_in()*1000 + System.currentTimeMillis()));
			componentAccessTokenDao.save(componentAccessToken);
			ComponentTokenManager.init(componentAppid, componentAppsecret,118,componentAccessTokenDao,componentVerifyTicketDao);
		}
		
	}
	
}

